<template>
  <div class="container-fluid">
    <div class="row school-model school-tiao">
      <div class="col school-tiao-left">
        <span>下课点评</span>
      </div>
      <div class="col text-right">
        <a-button-group>
          <a-button @click="setaddress = true" type="primary">添加补课学员</a-button>
          <a-button type="primary" @click="$router.go(-1)">返回</a-button>
        </a-button-group>
      </div>
    </div>
    <div class="row school-model index-model">
      <div class="col school-col-table">
        <table class="table table-borderless" v-if="schedule">
          <tbody>
            <tr>
              <td>
                <span>班级：</span>
                <span>{{schedule.schoolclazz.name}}</span>
              </td>
              <td>
                <span>教室：</span>
                <span>{{getschoolclassroombyid( schedule.schoolclassroomid).name}}</span>
              </td>
              <td>
                <span>课程：</span>
                <span>{{ schedule.info }}</span>
              </td>
            </tr>
            <tr>
              <td>
                <span>上课时间：</span>
                <span>{{totime(schedule.starttime)}} &nbsp;{{schedule.schoolclasstime}}</span>
              </td>
              <td>
                <span>教师：</span>
                <span>{{getschooluserbyid( schedule.schooluserid).name}}</span>
              </td>
              <td>
                <span>助教：</span>
                <span>{{ usernameids(schedule.schooluserids) }}</span>
              </td>
            </tr>
          </tbody>
        </table>
        <el-dialog class="school-form" title="添加补课人员" width="810px" :visible.sync="setaddress">
          <Makeuplessons
            v-bind="{submit, setaddress, setsubmit, schoolclazzscheduleid:Number(ID), student: datas, schedule}"
          ></Makeuplessons>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submit=true">确 定</el-button>
            <el-button @click="setaddress = false">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
    <div class="row school-model index-model">
      <div class="col school-col-table">
        <div
          class="float-left"
          v-for="(v, i ) in tableDatas"
          :key="`1classsigin${i}`"
          @click="changecalendr(v, i)"
        >
          <schoolcard
            v-bind="{type:v.calendar?v.calendar.state?'':'已评':'', name: v.name, imagesrc:v.headimg }"
          ></schoolcard>
        </div>
        <div class="float-none"></div>
      </div>
    </div>
    <el-drawer
      title
      :size="size"
      :before-close="handleClose"
      :visible.sync="drawer"
      direction="rtl"
    >
      <el-container>
        <el-header>
          <div class="row">
            <div class="col-2">
              <el-avatar :size="60" :src="student.headimg"></el-avatar>
            </div>
            <div class="col-3">
              <h3 style="line-height:60px;">{{student.name}}</h3>
            </div>
            <div class="col-6">
              <div class="d-inline-block" v-if="studID">
                <el-tag>补课人员</el-tag>
                <el-tag v-show="ruleForm.type === '补课'" >已完成补课</el-tag>
              </div>
            </div>
          </div>
        </el-header>
        <el-container>
          <el-aside width="60px"></el-aside>
          <el-main>
            <el-form
              :model="ruleForm"
              :rules="rules"
              ref="ruleForm"
              label-width="100px"
              size="mini"
            >
              <el-form-item label="上课状态" prop="type">
                <el-radio-group :disabled="studID || ruleForm.type === '补课'" v-model="ruleForm.type">
                  <el-radio label="上课">上课</el-radio>
                  <el-radio label="请假">请假</el-radio>
                  <el-radio label="补课">补课</el-radio>
                  <el-radio disabled label="其他">完成补课</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="使用课时" prop="hour">
                <el-input-number v-model="ruleForm.hour" :min="1" :max="10" label="描述文字"></el-input-number>
              </el-form-item>
              <el-form-item label="课堂评分" grade>
                <el-rate v-model="ruleForm.grade"></el-rate>
              </el-form-item>
              <el-form-item label="评价内容">
                <el-input v-model="ruleForm.data.title"></el-input>
              </el-form-item>
              <el-form-item label="添加图片">
                <el-upload
                  class="avatar-uploader"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :show-file-list="false"
                  :multiple="true"
                  accept="*/image"
                  :auto-upload="true"
                  :http-request="ossuploadimage"
                  ref="upload"
                  :limit="9"
                  :before-upload="beforeAvatarUpload"
                >
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <div style="width:500px;">
                  <el-image
                    style="width: 100px; height: 100px;"
                    class="float-left"
                    v-for="(v, i) in ruleForm.data.images"
                    :key="v"
                    :src="v"
                    @click="ruleForm.data.images.splice(i,1)"
                  ></el-image>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
              </el-form-item>
            </el-form>
          </el-main>
        </el-container>
      </el-container>
    </el-drawer>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  asynccreatschoolclazzstudentcalendar,
  asyncgetschoolclazzschedule,
  ossupload
} from "../../../../plugins/api.js";
import Makeuplessons from "../Makeuplessons/index.vue";
import schoolcard from "../../../../components/card.vue";
import { totime, messagesend2, isinclass } from "../../../utils.js";
import OSS from "ali-oss";
import uuid from "uuid/v4";
import * as moment from "moment";

export default {
  name: "checkclassevaluation",
  data() {
    return {
      rules: {
        type: [{ required: true, message: "请选择上课状态", trigger: "blur" }],
        hour: [{ required: true, message: "请添加课时", trigger: "blur" }],
        grade: [{ required: true, message: "请添加课堂评分", trigger: "blur" }]
      },
      size: "600",
      setaddress: false,
      drawer: false,
      title: "添加补课人员",
      student: {},
      ruleForm: {
        ID: "",
        type: "",
        hour: 1,
        schoolstudentid: "",
        grade: 5,
        schoolclazzscheduleid: "",
        data: {
          title: "",
          images: []
        }
      },
      schedule: null,
      submit: false
    };
  },
  props: ["ID"],
  async mounted() {
    this.start();
  },
  computed: {
    ...mapGetters([
      "getschoolclazz",
      "getschooluser",
      "getschoolclassroom",
      "getschoolstudent",
      "getuser",
      "getschoolclassroombyid",
      "getschooluserbyid",
      "getschoolstudentbyid"
    ]),
    tableDatas() {
      const { mystudent, otherstudent, ID, getschoolstudent } = this;
      let data = getschoolstudent.filter(v =>
        [...mystudent, ...otherstudent].includes(v.ID)
      );
      data = JSON.parse(JSON.stringify(data));
      return data.map(v => {
        const { schoolclazzstudentcalendar } = v;
        const d = schoolclazzstudentcalendar.find(
          vo => vo.schoolclazzscheduleid == ID
        );
        if (d) {
          v.calendartype = d.type;
          v.calendar = d;
        }
        return v;
      });
      // 获取补课人员
    },
    studID() {
      const { student, otherstudent } = this;
      if (student.ID) {
        return otherstudent.includes(student.ID);
      }
      return false;
    },
    otherstudent() {
      // 获取补课学生
      const { schedule, mystudent } = this;
      if (schedule) {
        const { schoolclazzstudentcalendar } = schedule;
        return schoolclazzstudentcalendar
          .filter(v => !mystudent.includes(v.schoolstudentid))
          .map(v => v.schoolstudentid);
      }
      return [];
    },
    mystudent() {
      // 获取在读学生
      const { schedule } = this;
      if (schedule) {
        const { schoolclazz, starttime } = schedule;
        const { schoolstudentschoolclazz } = schoolclazz;
        return isinclass(schoolstudentschoolclazz, starttime).map(
          v => v.schoolstudentid
        );
      }
      return [];
    },
    datas() {
      const { mystudent, getschoolstudent } = this;
      return getschoolstudent.filter(v => mystudent.includes(v.ID));
    }
  },
  watch: {
    $route() {
      this.start();
    }
  },
  methods: {
    totime,
    async start() {
      try {
        const schedule = await asyncgetschoolclazzschedule({
          ID: this.ID,
          uid: true
        });
        if (schedule.length === 0) {
          this.$router.push("/classevaluation");
        } else {
          this.schedule = schedule[0];
        }
      } catch (err) {
        this.$router.push("/");
        return;
      }
    },
    async submitForm() {
      this.$refs["ruleForm"].validate(async valid => {
        if (valid) {
          try {
            const { ruleForm } = this;
            await asynccreatschoolclazzstudentcalendar({
              ...ruleForm,
              state: false
            });
            this.$notify({
              title: "成功",
              message: "提交成功",
              type: "success"
            });
            if (ruleForm.state) {
              const { schedule, getuser } = this;
              const username = getuser.name;
              const { schoolstudentid } = ruleForm;
              const time = moment(schedule.starttime).format("YYYY-MM-DD");
              const { name } = this.getschoolstudentbyid(schoolstudentid);
              await messagesend2(
                schoolstudentid,
                name,
                schedule.info,
                time,
                username,
                this.ID
              );
            }
            await this.start();
            await this.$store.dispatch("actionschoolstudent");
            this.drawer = false;
          } catch (err) {
            this.$notify({
              title: "错误",
              message: "提交失败",
              type: "error"
            });
          }
        }
      });
    },
    changecalendr({ calendar, ...student }) {
      const { schedule } = this;
      this.student = student;
      try {
        this.$refs.upload.clearFiles();
        // eslint-disable-next-line no-empty
      } catch (_err) {}
      if (calendar) {
        const {
          ID = "",
          type = "",
          hour = schedule.hour,
          schoolstudentid = student.ID,
          grade = 5,
          schoolclazzscheduleid = schedule.ID,
          state = true,
          data = {}
        } = JSON.parse(JSON.stringify(calendar));
        let title = "";
        let images = [];
        if (data) {
          title = data.title ? data.title : "";
          images = data.images ? data.images : [];
        }
        this.ruleForm = {
          ID,
          type,
          hour,
          schoolstudentid,
          grade: Number(grade),
          schoolclazzscheduleid,
          state,
          data: {
            title,
            images
          }
        };
      } else {
        this.ruleForm = {
          ID: "",
          type: "",
          hour: schedule.hour,
          schoolstudentid: student.ID,
          grade: 5,
          schoolclazzscheduleid: schedule.ID,
          data: {
            title: "",
            images: []
          }
        };
      }
      this.drawer = true;
    },
    usernameids(id) {
      if (id) {
        const data = this.getschooluser.find(v => v.ID == id);
        return data ? data.name : "";
      }
      return "";
    },
    handleClose(done) {
      const { drawer } = this;
      if (drawer === true) {
        this.$confirm("确认关闭？")
          .then(() => {
            done();
          })
          .catch(() => {});
      }
    },
    async setsubmit(n) {
      this.setaddress = false;
      this.submit = n;
      await this.start();
    },
    async ossuploadimage(e) {
      try {
        const res = await ossupload();
        const client = new OSS({
          region: "oss-cn-qingdao",
          accessKeyId: res.accessKeyId,
          accessKeySecret: res.accessKeySecret,
          stsToken: res.securityToken,
          bucket: "cdn-hterobot"
        });
        const x = e.file.name.split(".");
        const name = x[x.length - 1];
        const url = `school/head/${uuid()}.${name}`;
        await client.put(`${url}`, e.file);
        this.ruleForm.data.images.push(`https://cdn.hterobot.com/${url}`);
      } catch (e) {
        console.error("error: %j", e);
      }
    },
    beforeAvatarUpload(file) {
      if (this.ruleForm.data.images.length >= 9) {
        this.$message.error("最多上传9张图");
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    }
  },
  components: {
    schoolcard,
    Makeuplessons
  }
};
</script>

<style lang="scss" scoped>
.index-model {
  margin-top: 13px;
}
.float-left {
  margin-left: 12px;
  margin-right: 24px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
